package org.minapp.idiom.base.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.minapp.idiom.module.sys.Sys_user;
import org.minapp.idiom.service.RoleService;
import org.minapp.idiom.service.UserService;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;

@IocBean
public class MyRealm extends AuthorizingRealm {
    private static final Log log = Logs.get();
    @Inject
    private UserService userService;
    @Inject
    private RoleService roleService;


    /**
     * 用户授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {


        return null;
    }

    /**
     * 身份认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 获取用户名
        String userName = (String)token.getPrincipal();
        Sys_user user = userService.fetch(Cnd.where("loginname", "=", userName));

        if (user!=null){
            AuthenticationInfo authInfo=   new SimpleAuthenticationInfo(user.getLoginname(),user.getPassword(),getName());
            return authInfo;
        }


        return null;
    }
}
